package com.daka.tools.wechatPay;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JsUtil {

    public static String generateConfigJson(String jsapiTicket, boolean debug, String appId, String url,
                                            String... jsApiList) {
        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString();
        // String signature = generateConfigSignature(nonceStr,
        // jsapi_ticket,timestamp+"",url);
        Map<String, String> map = sign(jsapiTicket, url, nonceStr, Long.toString(timestamp));
        return "{" + "\"debug\":" + debug + "," + "\"appId\":" + "\"" + appId + "\"" + "," + "\"timestamp\":" + timestamp + "," + "\"nonceStr\":" + "\"" + nonceStr + "\"" + "," + "\"signature\":" + "\"" + map.get("signature") + "\"" + "," + "\"jsApiList\":" + JsonUtil.toJSONString(jsApiList) + "}";
    }

    public static Map<String, String> sign(String jsapiTicket, String url, String nonce_str, String timestamp) {
        Map<String, String> ret = new HashMap<>();
        String string1;
        String signature = "";

        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        // System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapiTicket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
